<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chat demo</title>

  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html,body {
      height: 100%;
      background-color: #f5f5f5;
    }

    .chat-history {
      border: 1px solid darkred;
      height: 300px;
      flex-grow: 1; /* 让聊天记录区域占满剩余空间   */
      padding: 16px;
      overflow-y: auto;
    }

    .input-container {
      border: 1px solid darkgreen;
      padding: 16px;
        display: flex;
        justify-content: space-between;
    }

    .chat-container {
      height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }

    #message-input {
        flex-grow: 1;
        padding: 8px;
    }
    #send-button {
        margin-left: 8px;
        padding: 8px 16px;
    }

    .message {
        margin-bottom: 15px;
        display: flex;
    }

    .message-content {
        padding: 10px 15px;
        border-radius: 15px;
        max-width: 70%;
    }

    .user-message {
        justify-content: flex-end;
    }

    .ai-message {
        justify-content: flex-start;
    }

    .user-message .message-content {
        background: #007bff;
        color: white;
    }
    .ai-message .message-content {
        background: #e9ecef;
        color: black;
    }

  </style>
</head>
<body>

<div class="chat-container">
  <div class="chat-history" id="chat-history">

  </div>

  <div class="input-container">
    <input type="text" id="message-input" placeholder="输入消息...">
    <button id="send-button">发送</button>
  </div>

</div>

<script>
    const chatHistory = document.getElementById('chat-history')
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    sendButton.addEventListener('click',send);

    messageInput.addEventListener('keypress', (event) => {
        if (event.key === 'Enter') {
            send(); // 调用发送消息的函数
        }
    });


    function send() {
        const message = messageInput.value.trim(); //去除前后空格
        // alert(message)
        if (message) {
            addMessage(message);
            messageInput.value = '';

            setTimeout(() => {
                addMessage("来自AI的响应:" + message, true);

            },1000);
        }
    }

    function addMessage(content,isAI = false) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${isAI ? 'ai-message' : 'user-message'}`;

        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        messageContent.textContent = content;

        messageDiv.appendChild(messageContent);
        chatHistory.appendChild(messageDiv);

        chatHistory.scrollTop = chatHistory.scrollHeight; // 保持滚动条在底部
    }



</script>

</body>
</html>
